<?php

namespace common\services\goods;

use common\extensions\BaseService;
use common\models\goods\goods\GoodsStockModel;
use common\models\goods\goods\GoodsStockLogModel;

/**
 * Desc 商品库存服务类
 * @author HUI
 */
class GoodsStockService extends BaseService
{

    /**
     * 获取库存信息
     * @param string/array $id 商品ID
     * **/
    public static function getStock($id)
    {
        if (empty($id)) {
            return [];
        }
        $where = ['and', ['in', 'gid', $id], ['>', 'nums', 0]];
        return GoodsStockModel::getAll($where, 'gid,nums', '', 'gid');
    }


    // 库存校验——查询柜组库存是否足够
    public static function verify($goods)
    {
        try {
            if (empty($goods)) {
                throw new \Exception('参数异常，请反馈管理员');
            }
            $where = ['and', ['in', 'gid', array_column($goods, 'gid')], ['>', 'nums', 0]];
            $stock = GoodsStockModel::getAll($where, 'gid,nums', '', 'gid');
            foreach ($goods as $val) {
                if (!isset($stock[$val['gid']]) || $val['count'] > $stock[$val['gid']]['nums']) {
                    throw new \Exception($val['gid']);
                }
            }
            return self::jsonSuccess();
        } catch (\Exception $exc) {
            return self::jsonError($exc->getMessage());
        }
    }

    /**
     * 库存锁定-外层一定要加事务
     * @param array $goods 商品信息
     * @param string $order_sn 订单号
     * $warehouse_id 仓库柜组
     * * */
    public static function lock($goods, $order_sn)
    {
        try {
            if (empty($goods)) {
                throw new \Exception('商品参数异常');
            }
            foreach ($goods as $value) {
                $stock = GoodsStockModel::find()->where(['gid' => $value['gid']])->one();
                if (empty($stock)) {
                    throw new \Exception($value['name'] . '库存信息异常(' . $value['gid'] . ')');
                }
                if ($value['count'] > $stock['nums']) {
                    throw new \Exception($value['name'] . '库存不足，剩余库存：' . $stock['nums']);
                }
                // 库存日志变动
                $log_data = [
                    'gid' => $value['gid'],
                    'barcode' => $value['barcode'],
                    'type' => GoodsStockLogModel::TYPE_OUT,
                    'create_time' => date('Y-m-d H:i:s'),
                    'last' => $stock['nums'],
                    'curr' => $stock['nums'] - $value['count'],
                    'nums' => $value['count'],
                ];
                $res = GoodsStockLogModel::create($log_data);
                if (empty($res)) {
                    throw new \Exception('库存扣减异常，请稍后再试');
                }
                if (empty($stock->updateCounters(['nums' => 0 - $value['count']]))) {
                    throw new \Exception('库存扣减异常，请稍后再试');
                }

            }
            return self::jsonSuccess();
        } catch (\Exception $exc) {
            return self::jsonError($exc->getMessage());
        }
    }


    /**
     * 库存释放-外层一定要加事务
     * @param array $goods 商品信息
     * @param string $order_sn 订单号
     * @param int $wa
     * @param string $type 类型 refund or cancel
     * * */
    public static function release($goods)
    {
        try {
            if (empty($goods)) {
                throw new \Exception('商品参数异常');
            }
            foreach ($goods as $value) {

                $stock = GoodsStockModel::find()->where(['gid' => $value['gid']])->one();
                if (empty($stock)) {
                    throw new \Exception('商品库存信息异常');
                }
                // 库存日志变动
                $log_data = [
                    'gid' => $value['gid'],
                    'barcode' => $value['barcode'],
                    'type' => GoodsStockLogModel::TYPE_IN,
                    'create_time' => date('Y-m-d H:i:s'),
                    'last' => $stock['nums'],
                    'curr' => $stock['nums'] + $value['count'],
                    'nums' => $value['count'],
                ];
                $res = GoodsStockLogModel::create($log_data);
                if (empty($res)) {
                    throw new \Exception('库存扣减异常，请稍后再试');
                }
                if (empty($stock->updateCounters(['nums' => $value['count']]))) {
                    throw new \Exception('库存扣减异常，请稍后再试');
                }
            }

            return self::jsonSuccess();
        } catch (\Exception $exc) {
            return self::jsonError($exc->getMessage());
        }
    }
}
